package dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;

import model.User;
import model.User.UserStatus;


public class UserDao
{
	private static EntityManager em;

	private static EntityManager getEntityManeger()
	{
		if (em == null || em.isOpen() == false)
		{
			EntityManagerFactory emf = Persistence
					.createEntityManagerFactory("sk");
			em = emf.createEntityManager();
			return em;
		} else
			return em;
	}

	public static User getByUsernameAndPassword(String username, String password)
	{
		List<User> users = null;

		em = getEntityManeger();
		
		try
		{
			TypedQuery<User> getUsersQuery = em.createQuery(
					"FROM User u WHERE u.username = ? AND u.password = ?",
					User.class);

			getUsersQuery.setParameter(1, username);
			getUsersQuery.setParameter(2, password);
			// DigestUtils.md5DigestAsHex(password.getBytes()));

			users = getUsersQuery.getResultList();
			
		} catch (NullPointerException e)
		{
			System.out.println("Nu exista "+e.getMessage());
		}
		
		if (users == null || users.size() < 1)
		{
			return null;
		}
		return users.get(0);
	}
	
	
	public static User getByUsername(String username)
	{
		
		em = getEntityManeger();
		
		TypedQuery<User> getUsersQuery = em.createQuery(
				"FROM User u WHERE u.username = ?",
				User.class);

		getUsersQuery.setParameter(1, username);
		List<User> users = getUsersQuery.getResultList();
		return users.get(0);

		
	}
	
	
	public static void addUser(String username,String password)
	{
		em = getEntityManeger();		
		User user=new User();
		
		user.setStatus(UserStatus.offline);
		user.setUsername(username);
		user.setPassword(password);
		
		em.getTransaction().begin();
		em.persist(user);
		em.getTransaction().commit();
		
		
	}

}
